package com.job.admin.message.listener;

import com.alibaba.fastjson2.JSON;
import com.job.admin.message.constant.MessageConstant;
import com.job.admin.message.pojo.MessageItem;
import com.job.admin.message.service.MessageService;
import com.job.client.common.exception.MyselfException;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.DateTimeUtils;
import com.job.client.model.message.constant.ChatLogRabbitmqConstant;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class MessageListener {
    @Autowired
    private MessageService messageService;
    @RabbitListener(queues = ChatLogRabbitmqConstant.QUEUE_CHAT_LOG_ADMIN)
    public void saveMessage(String dataJSON){
        String messageId = null;
        MessageItem messageItem = null;
        try {
            Map<String, Objects> map = JSON.parseObject(dataJSON, Map.class);
            messageId = JSON.parseObject(JSON.toJSONString(map.get("messageId")), String.class); //对方用户的id
            messageItem = JSON.parseObject(JSON.toJSONString(map.get("messageItem")), MessageItem.class);
        } catch (Exception e) {
            new MyselfException(201,"后台消息队列JSON数据转换失败");
            return;
        }
        if(messageId == null || messageItem == null){
            new MyselfException(201,"后台消息队列数据为空");
            return;
        }
        messageItem.setTime(DateTimeUtils.createNowTime());
        messageItem.setStatus(MessageConstant.CONTENT_OTHER_STATUS);
        ResponseResult result = messageService.createConnect(MessageConstant.CUSTOMER_SERVICE, messageId, messageItem);
        if(result.getCode() != 200){
            new MyselfException(201,"创建用户会话失败");
            return;
        }
    }
}
